/*
 * Copyright (c) 2006, 2021, webrx.cn All rights reserved.
 *
 */
package cn.webrx;

import java.util.concurrent.TimeUnit;

/**
 * <p>Project: javaseapp - Ticket
 * <p>Powered by webrx On 2021-08-24 11:43:30
 * <p>Created by IntelliJ IDEA
 *
 * @author webrx [webrx@126.com]
 * @version 1.0
 * @since 16
 */
public class Ticket implements Runnable {
    private int num = 1000;

    public int getNum() {
        return num;
    }

    public void setNum(int num) {
        this.num = num;
    }

    public Ticket() {

    }

    public Ticket(int num) {
        this.num = num;
    }

    @Override
    public void run() {
        while (true) {
            //同步代段，同步锁 无论有多少个线程，批行此代码段时，其它线程必须等待
            synchronized (this) {
                String name = Thread.currentThread().getName();
                if (num > 0) {
                    System.out.printf("[%s] 售出一张票，剩余%d张票%n", name, --num);
                } else {
                    System.out.printf("[%s] 售已经售完。%n", name);
                    break;
                }
                try {
                    TimeUnit.SECONDS.sleep(1);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
